package com.lottery.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lottery.common.contants.ReQueryResult;
import com.lottery.common.entity.MemberInfo;
import com.lottery.common.dao.MemberInfoMapper;
import com.lottery.api.service.MemberInfoService;
import com.lottery.common.utils.AES;
import com.lottery.common.utils.MD5;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

import static com.lottery.common.contants.Constants.*;
import static com.lottery.common.contants.ReQueryResult.TYPE_ONE_HUNDRED_SEVEN_STR;

/**
 * <p>
 * 会员信息表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-09-23
 */
@Service
public class MemberInfoServiceImpl extends ServiceImpl<MemberInfoMapper, MemberInfo> implements MemberInfoService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private ReQueryResult result = new ReQueryResult();

    @Resource
    private MemberInfoMapper mim;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Integer saveAndCheck(MemberInfo memberInfo) {
        //数据库需要至少一条数据
        return mim.saveAndCheck(memberInfo);
    }


    /**
     * 用户登录
     * @param info
     * @return
     *
     * 登录逻辑 ： 使用设备id登录，存在此ID并且此id未绑定手机号 登陆成功。 查询 无此id 静默注册 登录成功
     */
    @Override
    public ReQueryResult loginMember(MemberInfo info) {
        MemberInfo param=new MemberInfo();

        QueryWrapper<MemberInfo> queryWrapper=new QueryWrapper<>(param);
        if(info.getLoginType()!=TYPE_THREE) {
            queryWrapper.eq("phone",info.getPhone());
            queryWrapper.eq("password",AES.Encrypt(info.getPassword()));
        }
        if (info.getLoginType()==TYPE_THREE){
            queryWrapper.eq("equipment_num",info.getPhone());
            queryWrapper.isNull("phone");
        }


        MemberInfo memberInfo=mim.selectOne(queryWrapper);
        if(memberInfo==null){
            if (info.getLoginType()!=TYPE_THREE){
                result.loginError(LOGIN_FAILURE);
                return result;
            }
            memberInfo=new MemberInfo();
            if (info.getLoginType()==TYPE_THREE){
                info.setNickName("游客-"+info.getPhone());
                Integer count = mim.saveIosNumAndCheck(info);
                if (count<=0){
                    logger.info(" ios 游客注册失败，请检查设备号 和 该设备是否已注册手机号");
                    result.loginError(TYPE_ONE_HUNDRED_SEVEN_STR);
                    return result;
                }
                memberInfo=mim.selectById(info.getId());
            }
        }
        info.setId(memberInfo.getId());
        return loginSub(info,memberInfo);
    }

    public ReQueryResult loginSub(MemberInfo memberInfo,MemberInfo info){
        result = new ReQueryResult();
        String token= MD5.md5(memberInfo.getPhone()+ UUID.randomUUID().toString());
        NutMap map=new NutMap();
        map.setv("phone",memberInfo.getPhone());
        map.setv("token",token);
        map.setv("tokenTime",System.currentTimeMillis());
        map.setv("memberId",memberInfo.getId());
        map.setv("identify",memberInfo.getMemberIdentify());
        map.setv("loginType",memberInfo.getLoginType());
        map.setv("expiredTime",info.getExpiredTime());
        redisTemplate.opsForHash().put("loginMap",memberInfo.getPhone(), JSON.toJSONString(map));
        //仅做返回，暂时不添加进缓存
        map.setv("member",info);
        result.setData(map);
        result.success(SUCCESS_DESC);
        return  result;
    }

}
